package leetcode;

/**
 * 23
 * 合并 k 个排序链表，返回合并后的排序链表。请分析和描述算法的复杂度。
 * <p>
 * 示例:
 * <p>
 * 输入:
 * [
 *   1->4->5,
 *   1->3->4,
 *   2->6
 * ]
 * 输出: 1->1->2->3->4->4->5->6
 * <p>
 *
 * @author: cuihao
 * @create: 2020-07-02 01:14
 **/
public class MergeKLists {

    public static ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }

        return merge(lists, 0, lists.length - 1);
    }

    public static ListNode merge(ListNode[] lists, int l, int r) {
        if (l == r) {
            return lists[l];
        }
        if (l > r) {
            return null;
        }
        int mid = (l + r) / 2;
        // 拆分
        ListNode left = merge(lists, l, mid);
        ListNode right = merge(lists, mid + 1, r);
        // 合并
        return mergeTwoLists(left, right);
    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode nextL1 = l1;
        ListNode nextL2 = l2;
        ListNode head = new ListNode();
        ListNode cur = head;
        while (nextL1 != null && nextL2 != null) {
            int a = nextL1.val;
            int b = nextL2.val;
            if (a < b) {

                cur.next = nextL1;
                cur = cur.next;
                nextL1 = nextL1.next;
            } else if (a > b) {
                cur.next = nextL2;
                cur = cur.next;
                nextL2 = nextL2.next;
            } else {
                cur.next = nextL1;
                cur = cur.next;
                nextL1 = nextL1.next;

                cur.next = nextL2;
                cur = cur.next;
                nextL2 = nextL2.next;
            }
        }

        // 替代两个while
        cur.next = nextL1 == null ? nextL2 : nextL1;
        return head.next;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(-1, new ListNode(5, new ListNode(1)));
        ListNode node1 = new ListNode(6, new ListNode(10));

        ListNode[] listNodes = new ListNode[4];
        listNodes[1] = node;
        listNodes[3] = node1;
        mergeKLists(listNodes);
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
